<?php

namespace Api\Cola;

use App\Cola\Amqp\Consumer\BillImportConsumer;
use App\Cola\Amqp\Producers\BillImportProducer;
use App\Cola\Amqp\Producers\BillSubmitProducer;
use App\Cola\Logic\ColaImportBill;
use App\Cola\Service\ColaBillService;
use App\Cola\Service\ColaTradeCateService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Mockery\Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

use Hyperf\Amqp\Producer;
use Hyperf\Context\ApplicationContext;

/**
 *
 * */
#[Controller]
class BillController extends ColaBaseController
{

    /**
     * @var ColaBillService
     */
    #[Inject]
    protected ColaBillService $billService;

    /**
     * @var ColaTradeCateService
     */
    #[Inject]
    protected ColaTradeCateService $tradeCateService;

    #[Inject]
    protected Producer $producer;

    /**
     * 账单列表
     * */
    #[GetMapping('list')]
    public function list()
    {

        try {
            $params = [
                'user_id' => colaUser()->getId(),
                'pay_source' => $this->request->input('pay_source'),
                'ledger_id' => $this->request->input('ledger_id'),
                'pay_time' => $this->request->input('pay_time'),
                'pay_time_start' => $this->request->input('pay_time_start'),
                'pay_time_end' => $this->request->input('pay_time_end'),
                'trade_cate_id' => $this->request->input('trade_cate_id'),
                'counterparty' => $this->request->input('counterparty'),
                'counterparty_account' => $this->request->input('counterparty_account'),
                'goods' => $this->request->input('goods'),
                'cash_flow' => $this->request->input('cash_flow'),
                'money' => $this->request->input('money'),
                'money_min' => $this->request->input('money_min'),
                'money_max' => $this->request->input('money_max'),
                'payment_method' => $this->request->input('payment_method'),
                'trade_status' => $this->request->input('trade_status'),
                'trade_sn' => $this->request->input('trade_sn'),
                'trade_store_sn' => $this->request->input('trade_store_sn'),
                'created_at' => $this->request->input('created_at'),
                'created_at_start' => $this->request->input('created_at_start'),
                'created_at_end' => $this->request->input('created_at_end')
            ];

            [$page, $size] = $this->getPageSize();

            $field = ['*'];
            $result = $this->billService->getApiList($params, $field, $page, $size);

            return $this->response->success('success', $result);

        } catch (Exception $exception) {
            return $this->response->error($exception->getMessage());
        }
    }
    /**
     * 账单列表
     * */
    #[PostMapping('add')]
    public function add()
    {

        try {
            $params = [
                'user_id' => colaUser()->getId(),
                'pay_source' => $this->request->input('pay_source') ?: 1,
                'ledger_id' => $this->request->input('ledger_id'),
                'pay_time' => $this->request->input('pay_time')?:date('Y-m-d H:i:s'),
                'trade_cate_id' => $this->request->input('trade_cate_id'),
                'counterparty' => $this->request->input('counterparty'),
                'counterparty_account' => $this->request->input('counterparty_account'),
                'goods' => $this->request->input('goods'),
                'cash_flow' => $this->request->input('cash_flow'),
                'money' => $this->request->input('money'),
            ];

            $message = new BillSubmitProducer($params);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $producer->produce($message);

            return $this->response->success('success');

        } catch (Exception $exception) {
            return $this->response->error($exception->getMessage());
        }
    }

    /**
     * 交易分类
     * */
    #[GetMapping('tradeCateList')]
    public function tradeCateList()
    {
        try {
            $params = [
                'keyword' => $this->request->input('keyword'),
                'status' => 1,
            ];

            [$page, $size] = $this->getPageSize();

            $result = $this->tradeCateService->getApiList($params, ['*'], $page, $size);

            return $this->response->success('success', $result);

        } catch (Exception $exception) {
            return $this->response->error($exception->getMessage());
        }

    }


    /**
     * 账单导入.
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[PostMapping('submitBillTask')]
    public function submitBillTask()
    {
        try {


            $userId = colaUser()->getId();
            $pay_source = $this->request->input('pay_source');
            $file = $this->request->input('file');
            // 生成任务ID
            $taskId = uniqid('', true);

//            $server = new ColaImportBill;
//            $result = $server->example($taskId,$userId,$pay_source,$file);
//
//            return $this->response->success('success', ['task_id' => $server]);

            // 将任务ID存储到 Redis 中，并设置过期时间为24个小时
            $redisKey = "bill_import_task:$taskId";
            cache()->set($redisKey, json_encode(['code' => 1, 'msg' => '处理中']), 3600 * 24);

            // 将导入任务加入异步队列
            $data = [
                'task_id' => $taskId,
                'user_id' => $userId,
                'source' => $pay_source,
                'file' => $file
            ];
            $message = new BillImportProducer($data);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $result = $producer->produce($message);

            return $this->response->success('success', ['task_id' => $taskId]);
        } catch (\Exception $exception) {
            return $this->response->error($exception->getMessage());
        }
    }

    /**
     * 查询任务状态.
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[GetMapping('checkBillTaskStatus')]
    public function checkBillTaskStatus()
    {
        // 获取任务ID
        $taskId = $this->request->input('task_id');

        // 查询任务状态，假设任务状态存储在 Redis 中
        $redisKey = "bill_import_task:$taskId";
        $taskResult = cache()->get($redisKey);
        $taskResult = $taskResult ? json_decode($taskResult, true) : null;

        if (!$taskResult) {
            $taskResult = ['code' => 3, 'msg' => '导入任务不存在,请重新上传'];
        }

        return $this->response->success($taskResult['msg'], $taskResult);
    }
}